package com.parkingspace.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.parkingspace.dao.*;
import com.parkingspace.entity.*;
import com.parkingspace.service.IUserService;
import com.parkingspace.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author Gapper
 * @since 2021-05-24
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserroleMapper userroleMapper;

    @Resource
    private WalletUserMapper walletUserMapper;

	@Resource
	private RoleMapper roleMapper;

	@Resource
	private CarMapper carMapper;

	@Resource
	private ParkingInformationMapper parkingInformationMapper;


	@Resource
	private RedisTemplate<String, Object> redisTemplate;

	@Resource
	private PropertyBetweenUserMapper propertyBetweenUserMapper;

	@Resource
	private PropertyMapper propertyMapper;



    @Override
    public Map<String, Object> findSome(String uaccount, String upass) throws Exception{
    	QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    	queryWrapper.eq("uaccount",uaccount);
    	queryWrapper.eq("upwd",upass);
	    User user = userMapper.selectOne(queryWrapper);
	    if (user == null) {
	    	throw new RuntimeException("查无此人!");
	    }
	    log.info("登录查询结果为:{}",user.toString());
	    QueryWrapper<Userrole> queryWrapper1 = new QueryWrapper<>();
	    queryWrapper1.eq("uid", user.getUid());
	    List<Userrole> userroles = userroleMapper.selectList(queryWrapper1);
	    Map<String, Object> map = new HashMap<>();
		map.put("uid",user.getUid());
	    String token = JwtUtils.createToken(user.getUname(), 36000);
	    map.put("token",token);

	    //存储用户名和ID到Redis
	    log.info("用户的uid为:{}",user.getUid());
	    for (Userrole userrole : userroles) {
		    if (userrole.getRid() == 1 || userrole.getRid() == 4) {
			    redisTemplate.opsForValue().set(user.getUname(), userrole.getRid(),30, TimeUnit.MINUTES);
			    map.put("role",userrole.getRid());
			    break;
		    } else {
			    map.put("role",0);
			    break;
		    }
	    }
	    log.info("测试rid:{}",String.valueOf(redisTemplate.opsForValue().get(user.getUname())));
	    return map;
    }

    @Override
    public Integer saveUser(User user) {
        //判断用户名是否已经被占用
        Map<String,Object> map = new HashMap<>();
        map.put("uname",user.getUname());
        List<User> users = userMapper.selectByMap(map);
        if (users.size() != 0){
            return -1;
        }

        //设置账号状态、用户状态为正常
        user.setUstate(String.valueOf(1));
        user.setUaccountStatus(0);
        int row = userMapper.insert(user);

        //注册成功时，初始化用户钱包
        if (row != 0){
            //获得用户id
            map = new HashMap<>();
            map.put("uname", user.getUname());
            List<User> userList = userMapper.selectByMap(map);
            Long uid = null;
            for (User u : userList) {
                uid = u.getUid();
            }
            //初始化钱包
            WalletUser walletUser = new WalletUser();
            walletUser.setUid(uid);
            walletUser.setRid((long) 2);
            walletUserMapper.insert(walletUser);

            WalletUser walletUser1 = new WalletUser();
            walletUser1.setUid(uid);
            walletUser1.setRid((long) 3);
            walletUserMapper.insert(walletUser1);
        }

        return row;
    }

	@Override
	public void getUserNum(String token, Integer id) throws Exception {
		String username = JwtUtils.getUsername(token);
		if (username == null || id == null) {
			throw new RuntimeException("请登录!");
		}
		redisTemplate.opsForValue().set(username, id,30, TimeUnit.MINUTES);
		log.info("测试rid2:{}",String.valueOf(redisTemplate.opsForValue().get(username)));
	}

	@Override
	public void updateVerified(String token, String uname, String idCard) throws Exception {
		String username = JwtUtils.getUsername(token);
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("uname",username);
		User user = new User();
		user.setTrueName(uname);
		user.setUidcard(idCard);
		boolean b = userMapper.update(user, queryWrapper) == 1;
		if(!b) {
			throw new RuntimeException("实名认证失败!");
		}
	}

	@Override
	public Integer realNameDetection(String token) throws Exception {
		String username = JwtUtils.getUsername(token);
		if (username != null) {
			QueryWrapper<User> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("uname",username);
			User user = userMapper.selectOne(queryWrapper);
			if (user != null && user.getUaccount() != null && user.getUpwd() != null) {
				return 1;
			}
		}
		return 0;
	}

	@Override
	public Map<String, Object> findByName(String token) throws Exception {
    Map<String, Object> map = new HashMap<>();
		String username = JwtUtils.getUsername(token);
		if (username == null) {
			throw new RuntimeException("请先进行登录!");
		}
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("uname", username);
		User user = userMapper.selectOne(queryWrapper);
		if (user == null) {
			throw new RuntimeException("查无此人!");
		}
		map.put("yonghu",user);
		QueryWrapper<ParkingInformation> q = new QueryWrapper<>();
		q.eq("parking_uid", user.getUid());
		Integer integer = parkingInformationMapper.selectCount(q);
		map.put("chewei",integer);

		return map;
	}

	@Override
	public Boolean updateUpass(String token, String oldPassword, String newPassword) throws Exception {
		String username = JwtUtils.getUsername(token);
		User user = new User();
    	user.setUname(username);
    	user.setUpwd(oldPassword);
    	QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    	queryWrapper.setEntity(user);
		boolean b = userMapper.selectCount(queryWrapper) == 1;
		if (!b) {
			throw new RuntimeException("输入错误!");
		}
		User u = new User();
		u.setUpwd(newPassword);
		QueryWrapper<User> q = new QueryWrapper<>();
		q.eq("uname", username);
		b = userMapper.update(u, q) == 1;
		if (!b) {
			throw new RuntimeException("密码修改失败!");
		}

		return b;
	}

	@Override
	public Boolean updateUser(String token, User user) throws Exception {
		String username = JwtUtils.getUsername(token);
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    	queryWrapper.eq("uname", username);
		boolean b = userMapper.update(user, queryWrapper) == 1;
		if (!b) {
			throw new RuntimeException("修改失败!");
		}
		return b;
	}

	@Override
	public Boolean deleteUser(String token) throws Exception {
		String username = JwtUtils.getUsername(token);
		Boolean delete = redisTemplate.delete(username);
		return delete;
	}

	@Override
	public List<User> findAll() {
		List<User> userList = userMapper.selectList(null);
		return userList;
	}

	@Override
	public boolean delete(Long uid) {
		int i = userMapper.deleteById(uid);
		if(i>0){
			return true;
		}else{
			return false;
		}

	}

	@Override
	public List<User> findBy(User user) {
    	if((user.getUname()!=null || !user.getUname().trim().equals("")) && (user.getUidcard()!=null) || !user.getUidcard().trim().equals("")){
			System.out.println(("bbbbbbbbbbbbbbbbbbbbbbbbbb"));
    		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
			queryWrapper.nested(qw -> qw.like("uname", user.getUname().trim()).or().like("true_name", user.getUname().trim()));
			queryWrapper.like("uidcard", user.getUidcard().trim());
			List<User> userList = userMapper.selectList(queryWrapper);
			return userList;
		}else if(user.getUidcard()==null || user.getUidcard().trim().equals("")){
			QueryWrapper<User> queryWrapper = new QueryWrapper<>();
			queryWrapper.like("uname", user.getUname().trim()).or().like("true_name", user.getUname().trim());
			List<User> userList = userMapper.selectList(queryWrapper);
			return userList;
		}else {
			QueryWrapper<User> queryWrapper = new QueryWrapper<>();
			queryWrapper.like("uidcard", user.getUidcard().trim());
			List<User> userList = userMapper.selectList(queryWrapper);
			return userList;
		}
	}



//	public List<User> findBy2(String uname,String propertyName) {
//		if((uname!=null || !uname.trim().equals("")) && (user.getUidcard()!=null) || !user.getUidcard().trim().equals("")){
//			QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//			queryWrapper.nested(qw -> qw.like("uname", user.getUname().trim()).or().like("true_name", user.getUname().trim()));
//			queryWrapper.like("uidcard", user.getUidcard().trim());
//			List<User> userList = userMapper.selectList(queryWrapper);
//			return userList;
//		}else if(user.getUidcard()==null || user.getUidcard().trim().equals("")){
//			QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//			queryWrapper.like("uname", user.getUname().trim()).or().like("true_name", user.getUname().trim());
//			List<User> userList = userMapper.selectList(queryWrapper);
//			return userList;
//		}else {
//			QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//			queryWrapper.like("uidcard", user.getUidcard().trim());
//			List<User> userList = userMapper.selectList(queryWrapper);
//			return userList;
//		}
//	}

	@Override
	public List<User> renterAll(User user) {
		QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("rname", "租客");
		List<Role> roles = roleMapper.selectList(queryWrapper);
		Map<String, Object> map = new HashMap<>();
		map.put("rid", roles.get(0).getRid());
		List<Userrole> userroles = userroleMapper.selectByMap(map);
		List<Long> list = new ArrayList<>();
		for (Userrole userrole:userroles){
			list.add(userrole.getUid());
		}
		List<User> userList = userMapper.selectBatchIds(list);

		List<User> userList1 = findBy(user);
		List<User> userList2 = new ArrayList<>();
		for(User us:userList){
			for(User us2:userList1){
				System.out.println("aaaaaaa"+us2);
				if(us.equals(us2)){
					userList2.add(us);
				}
			}
		}

		return userList2;
	}


	@Override
	public List<User> ownerAll(User user) {
		QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("rname", "业主");
		List<Role> roles = roleMapper.selectList(queryWrapper);
		Map<String, Object> map = new HashMap<>();
		map.put("rid", roles.get(0).getRid());
		List<Userrole> userroles = userroleMapper.selectByMap(map);
		List<Long> list = new ArrayList<>();
		for (Userrole userrole:userroles){
			list.add(userrole.getUid());
		}
		List<User> userList = userMapper.selectBatchIds(list);

		List<User> userList1 = findBy(user);
		List<User> userList2 = new ArrayList<>();
		for(User us:userList){
			for(User us2:userList1){
				if(us.equals(us2)){
					userList2.add(us);
				}
			}
		}

		return userList2;
	}


	@Override
	public List<PropertyQuery> propertyAll(String uname,String propertyName) {
		List<PropertyQuery> propertyQueryList = new ArrayList<>();
		QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("rname", "物业");
		List<Role> roles = roleMapper.selectList(queryWrapper);
		Map<String, Object> map = new HashMap<>();
		map.put("rid", roles.get(0).getRid());
		List<Userrole> userroles = userroleMapper.selectByMap(map);
		List<Long> list = new ArrayList<>();
		for (Userrole userrole:userroles){
			list.add(userrole.getUid());
		}
		List<User> userList = userMapper.selectBatchIds(list);

		QueryWrapper<User> queryWrapper2 = new QueryWrapper<>();
		queryWrapper2.like("uname", uname.trim()).or().like("true_name",uname);
		List<User> userList1 = userMapper.selectList(queryWrapper2);

		QueryWrapper<Property> queryWrapper3 = new QueryWrapper<>();
		queryWrapper3.like("property_name", propertyName);
		List<Property> properties = propertyMapper.selectList(queryWrapper3);

		List<Long> list1 = new ArrayList<>();
		for(Property property:properties){
			list1.add(property.getPropertyId());
		}

		List<PropertyBetweenUser> propertyBetweenUsers = propertyBetweenUserMapper.selectBatchIds(list1);
		List<Long> list2 = new ArrayList<>();
		for(PropertyBetweenUser pu:propertyBetweenUsers){
			list2.add(pu.getPbuUserId());
		}
		List<User> userList2 = userMapper.selectBatchIds(list2);

		List<User> userList3 = new ArrayList<>();
		for(User user:userList){
			for(User user1:userList1){
				for(User user2:userList2){
					if(user.equals(user1)&&user.equals(user2)){
						userList3.add(user);
					}
				}
			}
		}

		for(User user:userList3){
			PropertyQuery propertyQuery = new PropertyQuery();
			Long uid = user.getUid();

			Map<String, Object> map1 = new HashMap<>();
			map1.put("property_id", uid);
			List<ParkingInformation> parkingInformationList = parkingInformationMapper.selectByMap(map1);
			propertyQuery.setUser(user);
			propertyQuery.setParkingInformationList(parkingInformationList);

			Map<String, Object> map2 = new HashMap<>();
			map2.put("pbu_user_id", user.getUid());
			List<PropertyBetweenUser> propertyBetweenUserList = propertyBetweenUserMapper.selectByMap(map2);
			PropertyBetweenUser propertyBetweenUser = propertyBetweenUserList.get(0);
			Long pbuPropertyId = propertyBetweenUser.getPbuPropertyId();

			Property property = propertyMapper.selectById(pbuPropertyId);
			propertyQuery.setProperty(property);
			propertyQueryList.add(propertyQuery);
		}
		return propertyQueryList;
	}

	@Override
	public RenterQuery renterDetail(Long uid) {
		RenterQuery renterQuery = new RenterQuery();
		User user = userMapper.selectById(uid);
		Map<String, Object> map = new HashMap<>();
		map.put("uid", uid);
		List<Car> carList = carMapper.selectByMap(map);
		renterQuery.setCarList(carList);
		renterQuery.setUser(user);
		return renterQuery;
	}

	@Override
	public OwnerQuery ownerDetail(Long uid) {
		OwnerQuery ownerQuery = new OwnerQuery();
		User user = userMapper.selectById(uid);
		Map<String, Object> map = new HashMap<>();
		map.put("parking_id", uid);
		List<ParkingInformation> parkingInformationList = parkingInformationMapper.selectByMap(map);
		ownerQuery.setUser(user);
		ownerQuery.setParkingInformationList(parkingInformationList);
		return ownerQuery;
	}

	@Override
	public PropertyQuery propertyDetail(Long uid) {
		PropertyQuery propertyQuery = new PropertyQuery();
		User user = userMapper.selectById(uid);
		Map<String, Object> map = new HashMap<>();
		map.put("property_id", uid);
		List<ParkingInformation> parkingInformationList = parkingInformationMapper.selectByMap(map);
		propertyQuery.setUser(user);
		propertyQuery.setParkingInformationList(parkingInformationList);

		Map<String, Object> map2 = new HashMap<>();
		map2.put("pbu_user_id", user.getUid());
		List<PropertyBetweenUser> propertyBetweenUserList = propertyBetweenUserMapper.selectByMap(map2);
		PropertyBetweenUser propertyBetweenUser = propertyBetweenUserList.get(0);
		Long pbuPropertyId = propertyBetweenUser.getPbuPropertyId();

		Property property = propertyMapper.selectById(pbuPropertyId);
		propertyQuery.setProperty(property);
		return propertyQuery;
	}


}
